from typing import List

from langchain.schema import Document


def get_relevant_documents(
        query: str,
        es_client,
        index_name: str,
        embedding_model,
        default_filters: List[dict] = [],
        keyword_boost: float = 1.0,
        vector_boost: float = 1.0,
        **kwargs

) -> List[Document]:
    # 生成查询向量
    query_embedding = embedding_model.embed_query(query)

    # 从 kwargs 中获取动态过滤条件
    dynamic_filters = kwargs.get("filters", [])

    # 合并默认过滤条件和动态过滤条件
    combined_filters = default_filters + dynamic_filters

    # 构建混合查询
    search_body = {
        "query": {
            "bool": {
                "should": [  # 混合检索部分
                    {
                        "match": {
                            "text": {
                                "query": query,
                                "boost":keyword_boost
                            }
                        }
                    },
                    {
                        "script_score": {
                            "query": {"match_all": {}},
                            "script": {
                                "source": "cosineSimilarity(params.query_vector, 'vector') + 1.0",
                                "params": {"query_vector": query_embedding}
                            },
                            "boost": vector_boost
                        }
                    }
                ],
                "filter": combined_filters  # 条件过滤部分
            }
        }
    }

    # 执行查询
    response = es_client.search(
        index=index_name,
        body=search_body
    )

    # 转换为 Document 对象
    docs = []
    for hit in response['hits']['hits']:
        doc = Document(
            page_content=hit['_source']['text'],
            metadata=hit['_source'].get('metadata', {})
        )
        docs.append(doc)
    return docs
